<?php

namespace App\Jobs;

use App\Models\Order;
use App\Services\PayNotifyService;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class OrdersNotify implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * @var Order
     */
    protected $order;

    /**
     * 最大重试次数
     * @var int
     */
    public $tries = 3;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $payNotifyService = new PayNotifyService();
        $params = $payNotifyService->getNotifyParams($this->order);
        $client = (new Client())->get(rtrim($this->order->notify_url, '?') . '?' . urldecode(http_build_query($params)));
        $result = $client->getBody()->getContents();
        Log::info('异步通知:' . $this->order->trade_no);
        if ('success' !== strtolower($result)) {
            Log::info(substr($result,0, 10));
            $this->release($this->attempts() * 30);
        }
    }
}
